package com.lzy.mall.seckill.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.lzy.mall.common.constant.MQConstant;
import com.lzy.mall.common.to.mq.SeckillOrderTo;
import com.lzy.mall.common.utils.ResultUtils;
import com.lzy.mall.common.vo.MemberRespVo;
import com.lzy.mall.seckill.feign.CouponFeignService;
import com.lzy.mall.seckill.feign.ProductFeignService;
import com.lzy.mall.seckill.interceptor.LoginUserInterceptor;
import com.lzy.mall.seckill.vo.SeckillSessionWithSkusVo;
import com.lzy.mall.seckill.vo.SeckillSkuRedisTo;
import com.lzy.mall.seckill.vo.SkuInfoVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author lzy
 * @date 2021/10/14 14:06
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@Slf4j
public class SeckillService {

    private final CouponFeignService couponFeignService;

    private final StringRedisTemplate stringRedisTemplate;

    private final ProductFeignService productFeignService;

    private final RedissonClient redissonClient;

    private final RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKU_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    public void uploadSecKillSkuLatest() {
        List<SeckillSessionWithSkusVo> sessionWithSkusVos = couponFeignService.uploadSecKillSkuLatest();
        //缓存到Redis中
        //1、缓存活动的信息
        saveSessionInfos(sessionWithSkusVos);
        //2、缓存活动的关联商品信息
        saveSessionSkuInfos(sessionWithSkusVos);
    }

    /**
     * 缓存活动的关联商品信息
     */
    private void saveSessionSkuInfos(List<SeckillSessionWithSkusVo> sessionWithSkusVos) {
        sessionWithSkusVos.stream().forEach(session -> {
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            Boolean hasKey = stringRedisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = session.getRelationEntities().stream().map(item -> item.getPromotionSessionId().toString() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                //缓存活动信息
                stringRedisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    /**
     * 缓存活动的信息
     *
     * @param sessionWithSkusVos
     */
    private void saveSessionInfos(List<SeckillSessionWithSkusVo> sessionWithSkusVos) {
        sessionWithSkusVos.stream().forEach(session -> {
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(SKU_CACHE_PREFIX);
            session.getRelationEntities().forEach(seckillSkuVo -> {
                //4、商品的随机码
                String token = UUID.randomUUID().toString().replace("-", "");
                Boolean hasKey = ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString());
                if (!hasKey) {
                    //缓存商品
                    SeckillSkuRedisTo skuRedisTo = new SeckillSkuRedisTo();

                    //1、sku的基本数据
                    ResultUtils result = productFeignService.getSkuInfo(seckillSkuVo.getSkuId());
                    if (result.getCode() == 0) {
                        SkuInfoVo skuInfoVo = (SkuInfoVo) result.getBean(SkuInfoVo.class);
                        skuRedisTo.setSkuInfoVo(skuInfoVo);
                    }

                    //2、sku秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, skuRedisTo);

                    //3、设置当前商品的开始结束时间
                    skuRedisTo.setStartTime(session.getStartTime().getTime());
                    skuRedisTo.setEndTime(session.getEndTime().getTime());

                    //4、商品的随机码
                    skuRedisTo.setRandomCode(token);

                    String s = JSON.toJSONString(skuRedisTo);
                    ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), s);

                    //如果当前这个商品场次的商品已经上架就不用上架
                    //Boolean has = stringRedisTemplate.hasKey(SKU_STOCK_SEMAPHORE + token);

                    //5、使用库存作为分布式的信号量 限流：
                    //stringRedisTemplate.opsForValue().set(SKU_STOCK_SEMAPHORE + token,seckillSkuVo.getSeckillCount().toString());
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //商品可以秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVo.getSeckillCount());
                }
            });
        });
    }

    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");

        long now = DateUtil.date().getTime();
        for (String key : keys){
            String[] split = key.replace(SESSIONS_CACHE_PREFIX, "").split("_");
            long startTime = Long.parseLong(split[0]);
            long endTime = Long.parseLong(split[1]);
            if (now >= startTime && now <= endTime) {
                //2、获取这个秒杀场次需要的所有商品信息
                List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKU_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                if (CollUtil.isNotEmpty(list)){
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        SeckillSkuRedisTo seckillSkuRedisTo = JSONUtil.toBean(item, SeckillSkuRedisTo.class);
                        return seckillSkuRedisTo;
                    }).collect(Collectors.toList());

                    return collect;
                }
                break;
            }
        }
        return null;
    }

    public SeckillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKU_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (CollUtil.isNotEmpty(keys)){
            String regx = "\\d_" + skuId;
            for (String key : keys) {
                if(Pattern.matches(regx, key)){
                    String json = hashOps.get(key);
                    SeckillSkuRedisTo to = JSONUtil.toBean(json, SeckillSkuRedisTo.class);
                    // 处理一下随机码
                    long current = DateUtil.date().getTime();
                    if(current <= to.getStartTime() || current >= to.getEndTime()){
                        to.setRandomCode(null);
                    }
                    return to;
                }
            }
        }
        return null;
    }

    public String kill(String killId, String key, Integer num) {
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();

        long s1 = System.currentTimeMillis();
        //1、获取当前秒杀商品得合法性
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKU_CACHE_PREFIX);

        String s = hashOps.get(killId);
        //获取redis中存储信息
        if (StringUtils.isEmpty(s)) {
            return null;
        } else {
            SeckillSkuRedisTo redis = JSON.parseObject(s, SeckillSkuRedisTo.class);
            //1、检验时间合法性
            long time = new Date().getTime();
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long ttl = endTime - startTime;

            if (time >= startTime && time <= endTime) {
                //2、校验随机码和商品ID
                String randomCode = redis.getRandomCode();
                String skuId = redis.getPromotionSessionId() + "_" + redis.getSkuId();
                if (randomCode.equals(key) && skuId.equals(killId)) {
                    //3、验证购物的数量是否合理
                    if (num <= redis.getSeckillLimit()) {
                        //4、验证这个人是否购买过。幂等性；如果秒杀成功就去redis占一个位。userId_sessionId_skuId
                        //SETNX
                        String redisKey = respVo.getId() + "_" + skuId;
                        //自动过期
                        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功说明重来没有买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                //秒杀成功;
                                //快速下单，发送MQ消息 10ms
                                String timeId = IdUtil.objectId();
                                SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                                seckillOrderTo.setOrderSn(timeId);
                                seckillOrderTo.setMemberId(respVo.getId());
                                seckillOrderTo.setNum(num);
                                seckillOrderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                seckillOrderTo.setSkuId(redis.getSkuId());
                                seckillOrderTo.setSeckillPrice(new BigDecimal(redis.getSeckillPrice().toString()));
                                rabbitTemplate.convertAndSend(MQConstant.orderEventExchange, MQConstant.orderSeckillRK, seckillOrderTo);
                                long s2 = System.currentTimeMillis();
                                log.info("耗时...",(s2-s1));
                                return timeId;
                            }
                        }
                    }
                }
            }

        }

        return null;
    }
}
